var express = require('express')
const models = require("../../models");
const {success, error} = require("../../utils/message");
const checkPermission = require('../../middlewares/check-permission');
var router = express.Router()

// 文章列表
router.get('/', checkPermission(), async function (req, res, next) {
    let articles = await models.Article.findAll({
        include: [
            {
                model: models.Brand,
                as: 'brand'
            }
        ],
        order: [
            ['createdAt', 'DESC'],
        ],
    })
    success(res, '查询成功', {articles})
})

// 新增文章
router.post('/', checkPermission(), async function (req, res, next) {
    const title = req.body.title
    const content = req.body.content

    if (!title) {
        return error(res, '请填写文章标题')
    }

    if (!content) {
        return error(res, '请填写文章内容')
    }

    const articleTitle = await models.Article.findOne({where: {title: title}})
    if (articleTitle) {
        return error(res, '文章标题已存在，请勿重复添加')
    }

    let article = await models.Article.create(req.body)
    success(res, '新增成功', {article})
});

// 查询单条
router.get('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const article = await models.Article.findByPk(id)
    if (!article) {
        return error(res, '当前文章不存在，无法修改')
    }

    success(res, '查询成功', {article})
})

// 修改文章
router.put('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id
    const title = req.body.title
    const content = req.body.content

    if (!title) {
        return error(res, '请填写文章标题')
    }

    if (!content) {
        return error(res, '请填写文章内容')
    }

    const article = await models.Article.findByPk(id)
    if (!article) {
        return error(res, '当前文章不存在，无法修改')
    }

    article.update(req.body)
    success(res, '修改成功', {article})
})

// 删除文章
router.delete('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const article = await models.Article.findOne({
        where: {id: id},
    })

    article.destroy()
    success(res, '删除成功')
})
module.exports = router
